#include "send.h"


void DeviceFound(const DeviceInfo *device)
{
	int i;
	printf("<DeviceFound>CB: Device has found\n");
	printf("\tdevId=%s\n", device->devId);
	printf("\tdevName=%s\n", device->devName);
	printf("\tdevType=%d\n", device->devType);
	printf("\taddrNum=%d\n", device->addrNum);
	for (i = 0; i < device->addrNum; i++) {
		printf("\t\taddr%d:type=%d,", i + 1, device->addr[i].type);
		switch (device->addr[i].type) { 
		case CONNECTION_ADDR_WLAN:
		case CONNECTION_ADDR_ETH:
			printf("ip=%s,port=%d,", device->addr[i].info.ip.ip, device->addr[i].info.ip.port);
			break;
		default:
			break;
		}
		printf("peerUid=%s\n", device->addr[i].peerUid);
	}
	printf("\tcapabilityBitmapNum=%d\n", device->capabilityBitmapNum);
	for (i = 0; i < device->addrNum; i++) {
		printf("\t\tcapabilityBitmap[%d]=0x%x\n", i + 1, device->capabilityBitmap[i]);
	}
	printf("\tcustData=%s\n", device->custData);
}

void DiscoverySuccess(int subscribeId)
{
	printf("<DiscoverySuccess>CB: discover subscribeId=%d\n", subscribeId);
}

void DiscoveryFailed(int subscribeId, DiscoveryFailReason reason)
{
	printf("<DiscoveryFailed>CB: discover subscribeId=%d failed, reason=%d\n", subscribeId, (int)reason);
}

int DiscoveryInterface()
{
	SubscribeInfo info = {
		.subscribeId = g_publishID,
		.mode = DISCOVER_MODE_ACTIVE,
		.medium = COAP,
		.freq = LOW,
		.isSameAccount = false,
		.isWakeRemote = false,
		.capability = "osdCapability",
		.capabilityData = (unsigned char*)cData,
		.dataLen = strlen(cData) + 1,
	};
	IDiscoveryCallback cb = {
		.OnDeviceFound = DeviceFound,
		.OnDiscoverFailed = DiscoveryFailed,
		.OnDiscoverySuccess = DiscoverySuccess,
	};
	return StartDiscovery(pkgName, &info, &cb);
}

int SessionOpened(int sessionId, int result)
{
	printf("<SessionOpened>CB: session %d open ret=%d\n", sessionId, result);
	return 0;
}

void SessionClosed(int sessionId)
{
	printf("<SessionClosed>CB: session %d closed\n", sessionId);
}

void ByteRecived(int sessionId, const void *data, unsigned int dataLen)
{
	printf("<ByteRecived>CB: session %d received %u bytes data=%s\n", sessionId, dataLen, (const char *)data);
}

void MessageReceived(int sessionId, const void *data, unsigned int dataLen)
{
	printf("<MessageReceived>CB: session %d received %u bytes message=%s\n", sessionId, dataLen, (const char *)data);
}

const ISessionListener sessionCB = {
	.OnSessionOpened = SessionOpened,
	.OnSessionClosed = SessionClosed,
	.OnBytesReceived = ByteRecived,
	.OnMessageReceived = MessageReceived,
};

int OpenSessionInterface(const char *SessionName, const char *peerName, const char *peerId)
{
	SessionAttribute attr = {
		.dataType = TYPE_BYTES,
		.linkTypeNum = 1,
		.attr = {RAW_STREAM},
	};
	int lt = LINK_TYPE_WIFI_WLAN_2G;
	attr.linkType[0] = lt;
	return OpenSession(SessionName, peerName, peerId, "MyGroup", &attr);
}

void GetAllNodeDeviceInfoInterface(NodeBasicInfo **dev, int32_t *num)
{
	GetAllNodeDeviceInfo(pkgName, dev, num);
	printf("<GetAllNodeDeviceInfo>return %d Node\n", *num);
	for (int i = 0; i < *num; i++) {
		printf("<Node %d>deviceName=%s, networkId=%s, Type=%uud\n", i + 1, dev[i]->deviceName, dev[i]->networkId, dev[i]->deviceTypeId);
	}
}

void SendData()
{
	NodeBasicInfo *dev;
	int32_t dev_num;
	bool needContinue = true;

	GetAllNodeDeviceInfoInterface(&dev, &dev_num);
	if (dev_num) {
		int sessionId = OpenSessionInterface(sessionName, sessionName, dev[0].networkId);
		if (sessionId < 0) {
			printf("OpenSessionInterface fail, ret=%d\n", sessionId);
			return;
		}
		while (needContinue) {
			char op;
			SendBytes(sessionId, cData, strlen(cData) + 1);
			printf("Input s to stop:\n");

			op = getchar();
			switch(op) {
			case 's':
			case 'S':
				needContinue = false;
				break;
			default:
				break;
			}
		}
		CloseSession(sessionId);
	} else {
		printf("Get no Node\n");
	}
}

int _CreateSessionServer()
{
	return CreateSessionServer(pkgName, sessionName, &sessionCB);
}

int main(int argc, char **argv)
{
	int ret;

	ret = DiscoveryInterface();
	if (ret) {
		printf("DiscoveryInterface fail, ret=%d\n", ret);
		goto err_DiscoveryInterface;
	}
	ret = CreateSessionServer(pkgName, sessionName, &sessionCB);
	if (ret) {
		printf("CreateSessionServer fail, ret=%d\n", ret);
		goto err_CreateSessionServer;
	}
	SendData();
	RemoveSessionServer(pkgName, sessionName);
err_CreateSessionServer:
	StopDiscovery(pkgName, g_publishID);
err_DiscoveryInterface:
	return 0;
}

static int get_pid()
{
	char pid_buffer[20];
    int pid = -1;

    FILE *fd = fopen(TMP_PATH, "r");
    if (fd != NULL)
    {
        fread(pid_buffer,1, 20,fd);
        fclose(fd);

        pid = atoi(pid_buffer);
    }

    return pid;
}

void send_signal(int cmd)
{
    int pid_recv = get_pid();
	union sigval value;
	value.sival_int = cmd;

    if(pid_recv >0) 
    {
		printf("send %d to pid %d---", SIG_TYPE, pid_recv);
        if (sigqueue(pid_recv,SIG_TYPE,value)<0)
            printf("fail\n");
        else 
            printf("success\n");
    }
}

